const cloud = require("wx-server-sdk");
const xlsx = require('node-xlsx')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();
const _ = db.command;
// 获取openid
const getOpenId = async () => {
  // 获取基础信息
  const wxContext = cloud.getWXContext();
  return {
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  };
};

// 获取小程序二维码
const getMiniProgramCode = async () => {
  // 获取小程序二维码的buffer
  const resp = await cloud.openapi.wxacode.get({
    path: "pages/index/index",
  });
  const {
    buffer
  } = resp;
  // 将图片上传云存储空间
  const upload = await cloud.uploadFile({
    cloudPath: "code.png",
    fileContent: buffer,
  });
  return upload.fileID;
};

// 创建集合
const createCollection = async () => {
  try {
    // 创建集合
    await db.createCollection("admin_user");
    await db.collection("admin_user").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华东",
        city: "上海",
        admin_user: 11,
      },
    });
    await db.collection("admin_user").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华东",
        city: "南京",
        admin_user: 11,
      },
    });
    await db.collection("admin_user").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华南",
        city: "广州",
        admin_user: 22,
      },
    });
    await db.collection("admin_user").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华南",
        city: "深圳",
        admin_user: 22,
      },
    });
    return {
      success: true,
    };
  } catch (e) {
    // 这里catch到的是该collection已经存在，从业务逻辑上来说是运行成功的，所以catch返回success给前端，避免工具在前端抛出异常
    return {
      success: true,
      data: "create collection success",
    };
  }
};

// 查询所有数据
const selectRecord = async () => {
  // 返回数据库查询结果
  return await db.collection("admin_user").get();
};

// 根据手机号查询数据
const selectRecordByPhone = async (phone) => {
  console.log(phone, "phone");
  // 返回数据库查询结果
  return await db.collection("admin_user").where({
    phone: _.or(_.eq(Number(phone)), _.eq(phone))
    // phone: _.eq(Number(phone))
  }).get();
};

// 解析xlsx格式文件
const parseXlsxFile = async (fileID) => {
  try {
    // 1. 获取上传的Excel文件
    const res = await cloud.downloadFile({
      fileID: fileID
    })
    const buffer = res.fileContent

    // 2. 解析Excel文件
    const sheets = xlsx.parse(buffer)

    // 假设Excel文件只有一个工作表
    const sheet = sheets[0]
    const data = sheet.data

    // 3. 提取表头和数据
    const headers = data[0] // 第一行是表头
    const rows = data.slice(1) // 其余行是数据

    // 4. 将数据转换为对象数组
    const orders = rows.map(row => {
      let order = {}
      headers.forEach((header, index) => {
        // 处理带*号的必填字段
        const isRequired = header.startsWith('*')
        const fieldName = isRequired ? header.substring(1) : header
        order[fieldName] = row[index] || ''
      })
      return order
    })

    // 5. 数据验证
    const validatedOrders = []
    const errors = []

    orders.forEach((order, index) => {
      // 检查必填字段
      const requiredFields = ['年度', '交粮粮站', '乡镇', '姓名', '身份证号', '种植亩数', '单价(元/kg)', '种子领用(斤)', '银行名称', '联系方式']
      let isValid = true
      let errorMsg = ''

      requiredFields.forEach(field => {
        if (!order[field] || order[field].toString().trim() === '') {
          isValid = false
          errorMsg += `${field}不能为空; `
        }
      })

      // 验证身份证号格式
      if (order.身份证号 && !/^\d{17}[\dXx]$/.test(order.身份证号)) {
        isValid = false
        errorMsg += '身份证号格式不正确; '
      }

      if (isValid) {
        validatedOrders.push(order)
      } else {
        errors.push({
          row: index + 2, // Excel行号从1开始，表头占1行
          data: order,
          error: errorMsg
        })
      }
    })

    // 6. 处理数据入库（存在则更新，不存在则新增）
    let successCount = 0
    let updateCount = 0
    let addCount = 0

    for (const order of validatedOrders) {
      try {
        // 查询是否已存在相同年度和身份证号的记录
        const queryResult = await db.collection('peasant_data')
          .where({
            year: order.年度,
            idNumber: order.身份证号
          })
          .get();

        if (queryResult.data.length > 0) {
          // 存在则更新
          const docId = queryResult.data[0]._id
          await db.collection('peasant_data').doc(docId).update({
            data: {
              // county: "余庆",
              town: order.乡镇,
              acquisitionSitePoint: order.交粮粮站,
              orderPrice: parseFloat(order["单价(元/kg)"]),
              bz: order.备注,
              peasantName: order.姓名,
              year: order.年度,
              village: order.村,
              seedGetNum: order["种子领用(斤)"],
              orderPlantArea: order.种植亩数,
              group: order.组,
              phone: order.联系方式,
              idNumber: order.身份证号,
              bankCode: order.银行卡号,
              bankName: order.银行名称,
              // acquisitionDate: "",
              // sellNum: 0,
              // sellMoney: 0
            }
          })
          updateCount++
        } else {
          // 不存在则新增
          await db.collection('peasant_data').add({
            data: {
              // county: "余庆",
              town: order.乡镇,
              acquisitionSitePoint: order.交粮粮站,
              orderPrice: parseFloat(order["单价(元/kg)"]),
              bz: order.备注,
              peasantName: order.姓名,
              year: order.年度,
              village: order.村,
              seedGetNum: order["种子领用(斤)"],
              orderPlantArea: order.种植亩数,
              group: order.组,
              phone: order.联系方式,
              idNumber: order.身份证号,
              bankCode: order.银行卡号,
              bankName: order.银行名称,
              acquisitionDate: "",
              sellNum: 0,
              sellMoney: 0,
              registrant:""
            }
          })
          addCount++
        }
        successCount++
      } catch (err) {
        console.error(`处理第${order.行号}条数据时出错:`, err)
        errors.push({
          row: order.行号,
          data: order,
          error: err.message
        })
      }
    }

    // 7. 返回处理结果
    return {
      code: 0,
      message: '导入完成',
      data: {
        total: orders.length,
        success: successCount,
        added: addCount,
        updated: updateCount,
        failed: errors.length,
        errors: errors
      }
    }

  } catch (err) {
    console.error(err)
    return {
      code: -1,
      message: '导入失败',
      error: err.message
    }
  }
}


// 更新数据
const updateRecord = async (event) => {
  try {
    // 遍历修改数据库信息
    for (let i = 0; i < event.data.length; i++) {
      await db
        .collection("admin_user")
        .where({
          _id: event.data[i]._id,
        })
        .update({
          data: {
            admin_user: event.data[i].admin_user,
          },
        });
    }
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 新增数据
const insertRecord = async (event) => {
  try {
    const insertRecord = event.data;
    // 插入数据
    await db.collection("admin_user").add({
      data: {
        region: insertRecord.region,
        city: insertRecord.city,
        admin_user: Number(insertRecord.admin_user),
      },
    });
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 删除数据
const deleteRecord = async (event) => {
  try {
    await db
      .collection("admin_user")
      .where({
        _id: event.data._id,
      })
      .remove();
    return {
      success: true,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};
// const getOpenId = require('./getOpenId/index');
// const getMiniProgramCode = require('./getMiniProgramCode/index');
// const createCollection = require('./createCollection/index');
// const selectRecord = require('./selectRecord/index');
// const updateRecord = require('./updateRecord/index');
// const sumRecord = require('./sumRecord/index');
// const fetchGoodsList = require('./fetchGoodsList/index');
// const genMpQrcode = require('./genMpQrcode/index');
// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event.type, context);
  switch (event.type) {
    case "getOpenId":
      return await getOpenId();
    case "getMiniProgramCode":
      return await getMiniProgramCode();
    case "createCollection":
      return await createCollection();
    case "selectRecord":
      return await selectRecord();
    case "selectRecordByPhone":
      return await selectRecordByPhone(event.phone);
    case "parseXlsxFile":
      return await parseXlsxFile(event.fileID);
    case "updateRecord":
      return await updateRecord(event);
    case "insertRecord":
      return await insertRecord(event);
    case "deleteRecord":
      return await deleteRecord(event);
  }
};